package com.lwf.smartseniorcare.service;

import com.lwf.smartseniorcare.dto.ElderlyDTO;
import com.lwf.smartseniorcare.entity.Elderly;
import com.lwf.smartseniorcare.entity.User;
import com.lwf.smartseniorcare.repository.ElderlyRepository;
import com.lwf.smartseniorcare.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ElderlyService {

    @Autowired
    ElderlyRepository elderlyRepository;

    @Autowired
    UserRepository userRepository;

    // Convert Entity to DTO
    private ElderlyDTO convertToDTO(Elderly elderly) {
        ElderlyDTO dto = new ElderlyDTO();
        dto.setId(elderly.getId());
        dto.setName(elderly.getName());
        dto.setBirthDate(elderly.getBirthDate());
        dto.setGender(elderly.getGender());
        dto.setAddress(elderly.getAddress());
        dto.setPhone(elderly.getPhone());
        dto.setEmergencyContact(elderly.getEmergencyContact());
        dto.setEmergencyContactPhone(elderly.getEmergencyContactPhone());
        dto.setHealthCondition(elderly.getHealthCondition());
        dto.setMedications(elderly.getMedications());
        dto.setAllergies(elderly.getAllergies());
        dto.setActive(elderly.isActive());
        if (elderly.getCaretaker() != null) {
            dto.setCaretakerId(elderly.getCaretaker().getId());
        }
        return dto;
    }

    // Convert DTO to Entity
    private Elderly convertToEntity(ElderlyDTO dto) {
        Elderly elderly = new Elderly();
        if (dto.getId() != null) {
            elderly.setId(dto.getId());
        }
        elderly.setName(dto.getName());
        elderly.setBirthDate(dto.getBirthDate());
        elderly.setGender(dto.getGender());
        elderly.setAddress(dto.getAddress());
        elderly.setPhone(dto.getPhone());
        elderly.setEmergencyContact(dto.getEmergencyContact());
        elderly.setEmergencyContactPhone(dto.getEmergencyContactPhone());
        elderly.setHealthCondition(dto.getHealthCondition());
        elderly.setMedications(dto.getMedications());
        elderly.setAllergies(dto.getAllergies());
        elderly.setActive(dto.isActive());
        if (dto.getCaretakerId() != null) {
            User caretaker = userRepository.findById(dto.getCaretakerId())
                    .orElseThrow(() -> new RuntimeException("Caretaker not found"));
            elderly.setCaretaker(caretaker);
        }
        return elderly;
    }

    public List<ElderlyDTO> getAllElderly() {
        return elderlyRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public ElderlyDTO getElderlyById(Long id) {
        Elderly elderly = elderlyRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + id));
        return convertToDTO(elderly);
    }

    public ElderlyDTO createElderly(ElderlyDTO elderlyDTO) {
        Elderly elderly = convertToEntity(elderlyDTO);
        elderly = elderlyRepository.save(elderly);
        return convertToDTO(elderly);
    }

    public ElderlyDTO updateElderly(Long id, ElderlyDTO elderlyDTO) {
        Elderly elderly = elderlyRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + id));
        
        Elderly updatedElderly = convertToEntity(elderlyDTO);
        updatedElderly.setId(id); // Ensure we don't create a new entity
        
        elderly = elderlyRepository.save(updatedElderly);
        return convertToDTO(elderly);
    }

    public void deleteElderly(Long id) {
        Elderly elderly = elderlyRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + id));
        elderlyRepository.delete(elderly);
    }

    public List<ElderlyDTO> getElderlyByCaretaker(Long caretakerId) {
        User caretaker = userRepository.findById(caretakerId)
                .orElseThrow(() -> new RuntimeException("Caretaker not found"));
        return elderlyRepository.findByCaretaker(caretaker).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public List<ElderlyDTO> searchElderlyByName(String name) {
        return elderlyRepository.findByNameContainingIgnoreCase(name).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
}
